<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>采购申请</h3>
      <el-button size="small" type="success" @click="handleAdd">
        <i class="el-icon-plus" />
        新增
      </el-button>
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 搜索区域 - 使用 el-form 结构 -->
    <!-- <el-card class="search-card">
      <el-form
        :model="listQuery"
        ref="searchForm"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="商品:">
          <el-select
            v-model="listQuery.goodsId"
            @change="handleGoodsChanges"
            placeholder="请选择商品"
            clearable
            class="search-select"
          >
            <el-option
              v-for="item in goodsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库:">
          <el-select
            v-model="listQuery.warehouseId"
            @change="handleWarehouseChanges"
            placeholder="请选择仓库"
            clearable
            class="search-select"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="申请时间:">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            class="date-picker"
            @change="handleDateChange"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="状态:">
          <el-select
            v-model="listQuery.status"
            placeholder="请选择状态"
            clearable
            class="search-select"
            @change="handleStatusChange"
          >
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="审核中" :value="1"></el-option>
            <el-option label="已审核" :value="2"></el-option>
            <el-option label="已驳回" :value="-1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="申请部门:">
          <el-cascader
            v-model="listQuery.departmentId"
            :options="departmentList"
            :props="departmentProps"
            clearable
            placeholder="请选择部门"
            class="search-select"
            @change="handleDepartmentChange"
          ></el-cascader>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card> -->

    <!-- 操作按钮区域 -->
    <div class="table-operations-wrapper">
      <div class="table-operations">
        <el-form
          ref="searchForm"
          :model="listQuery"
          :inline="true"
          class="search-form"
        >
          <!-- <el-form-item label="商品:">
            <el-select
              v-model="listQuery.goodsId"
              placeholder="请选择商品"
              clearable
              class="search-select"
              @change="handleGoodsChanges"
            >
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item label="仓库:">
            <el-select
              v-model="listQuery.warehouseId"
              placeholder="请选择仓库"
              clearable
              class="search-select"
              @change="handleWarehouseChanges"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="申请时间:">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              class="date-picker"
              @change="handleDateChange"
            />
          </el-form-item>

          <el-form-item label="状态:">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              class="search-select"
              @change="handleStatusChange"
            >
              <el-option label="待审核" :value="0" />
              <el-option label="审核中" :value="1" />
              <el-option label="已审核" :value="2" />
              <el-option label="已驳回" :value="-1" />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="申请部门:">
            <el-cascader
              v-model="listQuery.departmentId"
              :options="departmentList"
              :props="departmentProps"
              clearable
              placeholder="请选择部门"
              class="search-select"
              @change="handleDepartmentChange"
            ></el-cascader>
          </el-form-item> -->

          <el-form-item class="search-buttons">
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
            >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button> -->
        <!-- <el-button size="small" type="success" @click="handleAdd">
            <i class="el-icon-plus"></i>
            新增
          </el-button> -->
        <!-- <el-button type="warning" size="small" @click="handleEdit">
            <i class="el-icon-edit"></i>
            修改
          </el-button> -->
        <!-- <el-button type="danger" size="small" @click="handleDelete">
            <i class="el-icon-delete"></i>
            批量删除
          </el-button> -->
      </div>

      <!-- 购物单录入区域 -->
      <!-- <div class="shopping-entry">
          <div class="attachment-info">
            <el-upload
              class="upload-demo"
              :show-file-list="false"
              :http-request="handleUpload"
            >
              <el-link type="primary" class="upload-link">
                <i class="el-icon-paperclip"></i> 上传附件
              </el-link>
            </el-upload>
            <span v-if="uploadedFile" class="file-name">
              <i class="el-icon-document"></i> {{ uploadedFile.name }}
              <i class="el-icon-delete" @click="removeFile"></i>
            </span>
          </div>
        </div> -->
    </div>

    <!-- 商品表格区域 -->
    <el-table
      :data="demandList"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column> -->
      <el-table-column type="index" label="序号" width="80" align="center" />

      <el-table-column label="商品明细" width="450" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.list && scope.row.list.length > 0"
            class="goods-detail-container"
          >
            <!-- 将每个商品项水平排列 -->
            <div
              v-for="(item, index) in scope.row.list"
              :key="index"
              class="goods-item"
            >
              <!-- 商品名称 -->
              <div class="goods-name">{{ item.goodsName }}</div>

              <!-- 商品类型 -->
              <div class="goods-type">{{ item.goodsTypeName }}</div>

              <!-- 数量 -->
              <div class="goods-number">
                数量: <span class="number-value">{{ item.number }}</span>
              </div>

              <!-- 价格 -->
              <div class="goods-money">
                {{ formatPrice(item.money) }}
              </div>
            </div>
          </div>
          <div v-else class="no-goods">暂无商品</div>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="directorName"
        label="负责人"
        width="120"
      />

      <el-table-column
        align="center"
        prop="needDepartmentName"
        label="部门"
        width="180"
      />

      <el-table-column
        align="center"
        prop="operatorName"
        label="操作人"
        width="150"
      />

      <el-table-column
        align="center"
        prop="askType"
        label="需求类型"
        width="150"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.askType === 1"
            type="success"
          >月度采购</el-tag>
          <el-tag v-else type="danger">紧急采购</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="createTime"
        label="创建时间"
        width="180"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="270" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="operation-buttons">
            <!-- 新增购货单按钮 -->
            <div v-if="canAddPurchase(scope.row)" class="button-container">
              <el-button
                type="warning"
                size="mini"
                @click="handleAddPurchase(scope.row)"
              >
                新增购货
              </el-button>
            </div>
            <div v-else class="button-placeholder" />

            <!-- 编辑按钮 -->
            <div class="button-container">
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
            </div>

            <!-- 删除按钮 -->
            <div class="button-container">
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 合计行 -->
    <!-- <div class="summary-row">
        <div class="summary-label">合计:</div>
        <div style="flex-grow: 1"></div>
        <div style="margin-right: 15px">数量: {{ totalQuantity }}</div>
      </div> -->

    <!-- 分页组件 -->
    <el-row
      v-if="false"
      :gutter="10"
      style="margin-top: 20px"
      type="flex"
      justify="end"
    >
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 新增申请对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="75%"
    >
      <el-form
        ref="demandForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <!-- 需求类型 -->
        <el-form-item label="需求类型" prop="askType">
          <el-radio-group v-model="form.askType">
            <el-radio :label="1">月度采购</el-radio>
            <el-radio :label="2">紧急采购</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 商品明细表格 -->
        <el-form-item label="商品明细">
          <div class="goods-table-container">
            <el-table
              :data="form.goodsList"
              border
              style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            >
              <el-table-column align="center" label="仓库" width="180">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'goodsList.' + scope.$index + '.warehouseId'"
                    :rules="{
                      required: true,
                      message: '请选择仓库',
                      trigger: 'change',
                    }"
                    class="mb-0"
                  >
                    <el-select
                      v-model="scope.row.warehouseId"
                      placeholder="请选择仓库"
                      style="width: 100%"
                      @change="() => handleWarehouseChange(scope.$index)"
                    >
                      <el-option
                        v-for="item in warehouseList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="商品名称" width="300" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'goodsList.' + scope.$index + '.goodsId'"
                    :rules="{
                      required: true,
                      message: '请选择商品',
                      trigger: 'change',
                    }"
                    class="mb-0"
                  >
                    <el-select
                      v-model="scope.row.goodsId"
                      placeholder="请选择商品"
                      style="width: 100%"
                      filterable
                      remote
                      reserve-keyword
                      :remote-method="remoteSearchGoods"
                      :loading="goodsLoading"
                      popper-class="goods-select-dropdown"
                      @change="
                        (val) => handleGoodsItemChange(val, scope.$index)
                      "
                    >
                      <el-option
                        v-for="item in goodsList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                        <div class="goods-option-layout">
                          <span class="goods-name">{{ item.name }}</span>
                          <span v-if="item.model" class="goods-model">{{
                            item.model
                          }}</span>
                          <span
                            v-if="item.price"
                            class="goods-price"
                          >¥{{ item.price }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                align="center"
                prop="model"
                label="规格型号"
                width="170"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'goodsList.' + scope.$index + '.model'"
                    class="mb-0"
                  >
                    <el-input
                      v-model="scope.row.model"
                      placeholder="规格型号"
                      readonly
                      disabled
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="数量" width="120" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'goodsList.' + scope.$index + '.number'"
                    :rules="{
                      required: true,
                      message: '请输入数量',
                      trigger: 'blur',
                    }"
                    class="mb-0"
                  >
                    <el-input
                      v-model.number="scope.row.number"
                      type="number"
                      min="1"
                      placeholder="数量"
                      @input="() => updateMoney(scope.$index)"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="金额" width="150" align="center">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'goodsList.' + scope.$index + '.money'"
                    :rules="{
                      required: true,
                      message: '请输入金额',
                      trigger: 'blur',
                    }"
                    class="mb-0"
                  >
                    <el-input
                      v-model="scope.row.money"
                      placeholder="金额"
                      readonly
                      disabled
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                align="center"
                prop="stockNumber"
                label="库存余额"
                width="120"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'goodsList.' + scope.$index + '.stockNumber'"
                    class="mb-0"
                  >
                    <el-input
                      v-model="scope.row.stockNumber"
                      placeholder="库存余额"
                      readonly
                      disabled
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click.prevent="removeGoodsItem(scope.$index)"
                  />
                </template>
              </el-table-column>
            </el-table>

            <div class="add-goods-btn">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="addGoodsItem"
              >
                添加商品
              </el-button>
            </div>
          </div>
        </el-form-item>
        <!--
        <el-form-item label="需求部门" prop="needDepartmentId">
          <el-cascader
            v-model="form.needDepartmentId"
            :options="departmentList"
            :props="{
              label: 'name',
              value: 'id',
              children: 'list',
              disabled: (node) => !node.parent, // 第一层没有parent，所以禁用
              emitPath: false, // 只返回选中节点的值，而不是整个路径
            }"
            placeholder="请选择需求部门"
            clearable
            filterable
            @focus="onDepartmentFocus"
            @blur="onDepartmentBlur"
            @change="onDepartmentChange"
            style="width: 100%"
            :loading="departmentLoading"
          />
        </el-form-item> -->

        <el-form-item label="负责人" prop="directorId">
          <el-select
            v-model="form.directorId"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
            :loading="directorLoading"
            clearable
            remote
            :remote-method="searchDirectors"
            @focus="onDirectorFocus"
          >
            <el-option
              v-for="item in directorList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item label="上传文件" prop="askUrl">
          <el-upload
            class="upload-demo"
            drag
            :show-file-list="false"
            :http-request="handleUpload"
            :before-upload="beforeUpload"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
          <div v-if="uploadedFileName" class="uploaded-file-info">
            <span class="file-name">{{ uploadedFileName }}</span>
            <i class="el-icon-delete" @click.stop="removeImage" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 在页面底部添加税率输入弹框 -->
    <el-dialog
      title="设置税率"
      :visible.sync="taxRateDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="taxRateForm" label-width="80px">
        <el-form-item label="税率(%)" prop="taxRate">
          <el-input-number
            v-model="taxRateForm.taxRate"
            :min="0"
            :max="100"
            :precision="2"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="taxRateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTaxRate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  selAskListApi,
  addAskApi,
  updateAskByIdApi,
  delAskByIdApi,
  uploadFileApi,
  addOKBuyGoodsApi
} from '@/api/applyfor'
import {
  selGoodsListApi,
  selGoodsByIdApi,
  selGoodsNumberByIdApi
} from '@/api/goods'
import {
  selWarehouseListApi,
  selStaffListApi,
  selDepartmentListApi
} from '@/api/system'
import { mapGetters } from 'vuex'
export default {
  name: 'PurchaseDorder',
  data() {
    return {
      isFilterVisible: false, // 控制筛选区域显示/隐藏
      scanEnabled: false,
      orderData: {
        supplier: '',
        salesPerson: '',
        orderDate: '2025-03-24',
        deliveryDate: '2025-03-24',
        orderType: 'purchase',
        deliveryAddress: '',
        remark: '',
        discountRate: '0',
        discountAmount: '0',
        discountedAmount: '0.00',
        deliveryMethod: ''
      },
      salesPersonOptions: [
        { value: 'admin', label: '管理员' },
        { value: 'zhangsan', label: '张三' },
        { value: 'lisi', label: '李四' }
      ],
      addressOptions: [
        { value: 'address1', label: '广州市天河区某某路123号' },
        { value: 'address2', label: '深圳市南山区某某路456号' }
      ],
      deliveryMethodOptions: [
        { value: 'express', label: '快递' },
        { value: 'self', label: '自提' },
        { value: 'delivery', label: '送货' }
      ],
      warehouseOptions: [
        { value: 'warehouse1', label: '主仓库' },
        { value: 'warehouse2', label: '次仓库' }
      ],
      tableData: [
        {
          id: 1,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 2,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 3,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 4,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        },
        {
          id: 5,
          productName: '',
          productImage: '',
          brand: '',
          productRemark: '',
          attribute: '',
          unit: '',
          warehouse: '',
          availableStock: 0,
          quantity: 0,
          batchNumber: '',
          packageType: 'whole'
        }
      ],
      // 新增表单
      addForm: {
        demandType: 1,
        demandMoney: 1
      },
      totalQuantity: 0,
      multipleSelection: [],
      // 分页相关
      listQuery: {
        directorId: null, // 主管ID
        endTime: null, // 结束时间
        goodsId: null, // 商品ID
        page: 1, // 当前页
        pageSize: 10, // 每页条数
        startTime: null, // 开始时间
        status: null, // 状态
        warehouseId: null, // 仓库ID
        departmentId: [] // 部门ID
      },
      // 查询参数
      goodsQuery: {
        goodsTypeId: null,
        name: '',
        page: 1,
        pageSize: 9999,
        supplierId: null,
        warehouseId: null,
        model: ''
      },
      // 仓库列表查询
      warehouseQuery: {
        page: 1,
        pageSize: 9999,
        name: ''
      },
      // 职员列表
      staffQuery: {
        page: 1,
        pageSize: 9999,
        name: '',
        mobile: '',
        parent: ''
      },
      // 部门列表
      departmentQuery: {
        page: 1,
        pageSize: 9999,
        name: ''
      },
      total: 0, // 总条数
      listLoading: false, // 加载状态
      selectionRow: [], // 选中的行
      // 表单数据
      form: {
        askType: 1,
        goodsList: [{ goodsId: '', number: 1, money: '' }],
        // needDepartmentId: "",
        directorId: '',
        remark: '',
        askUrl: '',
        operatorId: this.$store.getters.userId
      },
      // 表单验证规则
      rules: {
        askType: [
          { required: true, message: '请选择需求类型', trigger: 'change' }
        ],
        // needDepartmentId: [
        //   { required: true, message: "请选择部门", trigger: "change" },
        // ],
        directorId: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
        goodsList: [
          {
            required: true,
            validator: this.validateGoodsList,
            trigger: 'change'
          }
        ]
      },
      dialogFormVisible: false,
      goodsList: [], // 商品列表
      warehouseList: [], // 仓库列表
      userList: [], // 用户列表
      demandList: [], // 需求列表
      dateRange: [], // 日期范围
      directorList: [], // 主管列表
      orderNo: 'GHDD202503240001',
      uploadedFile: null, // 保存已上传文件信息
      uploadedFileName: '', // 用于显示文件名
      currentGoodsPrice: 0, // 添加一个变量存储当前商品单价
      editMode: false,
      goodsLoading: false,
      departmentList: [], // 原始部门数据
      departmentProps: {
        checkStrictly: true, // 可以选择任意一级
        value: 'id',
        label: 'name',
        children: 'list', // 直接使用原始数据中的list字段
        disabled: (node) => !node.parent, // 第一层没有parent，所以禁用
        emitPath: false // 只返回选中节点的值，而不是整个路径
      },
      directorLoading: false,
      departmentLoading: false,
      taxRateDialogVisible: false,
      taxRateForm: {
        taxRate: 13 // 默认税率
      },
      currentRow: null, // 当前选中的行
      goodsName: ''
    }
  },
  computed: {
    dialogTitle() {
      return this.editMode ? '编辑' : '新增'
    },
    ...mapGetters(['userId'])
  },
  watch: {
    // 监视goodsList数组中每个元素的number属性
    'form.goodsList': {
      deep: true,
      handler(newVal) {
        // 当goodsList发生变化时，更新相应的金额
        if (newVal && newVal.length > 0) {
          newVal.forEach((item, index) => {
            if (item.goodsId && item.number) {
              this.updateMoney(index)
            }
          })
        }
      }
    }
  },
  created() {
    if (this.$route.query) {
      console.log(this.$route.query.status)
      this.listQuery.status = this.$route.query.status
    }
    this.applyForList()
    this.selGoodsList()
    this.selWarehouseList()
    this.selStaffList()
    this.fetchDepartmentData()
  },
  methods: {
    // 获取列表数据
    async applyForList() {
      this.listLoading = true
      try {
        const res = await selAskListApi(this.listQuery)
        this.demandList = res.records || []
        this.total = res.total || 0
      } catch (error) {
        console.error('获取列表失败:', error)
        this.$message({
          type: 'error',
          message: '获取列表失败: ' + (error.message || '未知错误')
        })
      } finally {
        this.listLoading = false
      }
    },
    // 获取商品列表
    async selGoodsList() {
      this.goodsLoading = true
      try {
        const res = await selGoodsListApi(this.goodsQuery)
        this.goodsList = res.records || []
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败')
        this.goodsList = []
      } finally {
        this.goodsLoading = false
      }
    },

    // 获取仓库列表
    async selWarehouseList() {
      const res = await selWarehouseListApi(this.warehouseQuery)
      this.warehouseList = res.records || []
    },
    // 职工列表
    async selStaffList() {
      const res = await selStaffListApi(this.staffQuery)
      this.directorList = res.records || []
    },
    // 获取部门列表
    async fetchDepartmentData() {
      this.departmentLoading = true
      try {
        const res = await selDepartmentListApi(this.departmentQuery)
        if (res.code === 1) {
          // 直接使用原始数据，无需任何转换
          this.departmentList = res.data
        }
        this.departmentLoading = false
      } catch (error) {
        console.error('获取部门数据失败:', error)
        this.departmentLoading = false
      }
    },
    // 商品改变
    handleGoodsChanges(val) {
      console.log(val)
      this.applyForList()
    },
    // 处理仓库变更
    handleWarehouseChange(index) {
      const warehouseId = this.form.goodsList[index].warehouseId
      const warehouse = this.warehouseList.find(
        (item) => item.id === warehouseId
      )

      if (warehouse) {
        // this.form.goodsList[index].warehouseName = warehouse.name;

        // 更新商品查询参数中的仓库ID
        this.goodsQuery.warehouseId = warehouseId

        // 清空当前行的商品选择
        this.form.goodsList[index].goodsId = ''
        this.form.goodsList[index].money = ''

        // 重新加载该仓库的商品列表
        this.selGoodsList()
      }
    },
    // 状态改变
    handleStatusChange(val) {
      this.applyForList()
    },
    // 日期改变
    handleDateChange(val) {
      if (val) {
        // 设置开始时间为当天的 00:00:00
        const startDate = new Date(val[0])
        startDate.setHours(0, 0, 0, 0)
        this.listQuery.startTime = Math.floor(startDate.getTime() / 1000)

        // 设置结束时间为当天的 23:59:59
        const endDate = new Date(val[1])
        endDate.setHours(23, 59, 59, 999)
        this.listQuery.endTime = Math.floor(endDate.getTime() / 1000)
      } else {
        this.listQuery.startTime = ''
        this.listQuery.endTime = ''
      }
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.applyForList()
    },

    // 重置搜索
    resetFilter() {
      this.dateRange = []
      this.listQuery = {
        directorId: null,
        endTime: '',
        goodsId: null,
        page: 1,
        pageSize: 10,
        startTime: '',
        status: null,
        warehouseId: null,
        departmentId: []
      }
      this.applyForList()
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.applyForList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.applyForList()
    },

    // 新增按钮点击
    handleAdd() {
      this.editMode = false
      this.resetForm()
      this.dialogFormVisible = true
    },

    // 编辑按钮点击
    handleEdit(row) {
      // 先重置表单
      this.resetForm()

      console.log('编辑行数据:', row)
      this.editMode = true

      // 确保所有必要字段都被设置
      this.form = {
        id: row.id,
        askType: row.askType,
        // needDepartmentId: row.needDepartmentId,
        directorId: row.directorId,
        remark: row.remark || '',
        askUrl: row.askUrl || '',
        operatorId: row.operatorId || this.$store.getters.userId,
        goodsList:
          Array.isArray(row.list) && row.list.length > 0
            ? row.list.map((item) => ({
              goodsId: item.goodsId,
              number: item.number,
              money: item.money,
              warehouseId: item.warehouseId,
              model: item.model
            }))
            : [{ goodsId: '', number: 1, money: '' }]
      }

      // 调试信息
      console.log('设置表单数据:', JSON.stringify(this.form))

      if (row.askUrl) {
        this.uploadedFileName = row.askUrl.split('/').pop()
      }

      this.dialogFormVisible = true
    },

    // 重置表单
    resetForm() {
      this.form = {
        askType: 1,
        goodsList: [{ goodsId: '', number: 1, money: '' }],
        needDepartmentId: '',
        directorId: '',
        remark: '',
        askUrl: '',
        operatorId: this.$store.getters.userId
      }
      this.uploadedFileName = ''
    },

    // 提交表单
    submitForm() {
      this.$refs.demandForm.validate(async(valid) => {
        if (valid) {
          try {
            // 显示加载状态
            const loading = this.$loading({
              lock: true,
              text: '提交中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })

            // 处理商品数据，确保类型正确
            const askGoods = this.form.goodsList.map((item) => {
              return {
                goodsId: parseInt(item.goodsId, 10), // integer
                number: parseInt(item.number, 10), // integer
                money: parseFloat(item.money || 0) // number
              }
            })

            // 创建符合接口规范的请求数据
            const postData = {
              askType: parseInt(this.form.askType, 10), // integer(int32)
              askUrl: this.form.askUrl || '', // string
              directorId: this.form.directorId || '', // string
              // needDepartmentId: this.form.needDepartmentId.toString(), // string (根据接口文档是string)
              operatorId:
                this.form.operatorId || this.$store.getters.userId || '', // string
              remark: this.form.remark || '', // string
              askGoods: askGoods // array
            }

            // 判断是否为编辑模式
            const isEdit = !!this.form.id

            // 编辑模式需要添加ID
            if (isEdit) {
              postData.id = parseInt(this.form.id, 10) // integer(int32)
            }

            console.log(
              `准备${isEdit ? '更新' : '新增'}数据:`,
              JSON.stringify(postData)
            )

            // 根据是否有id决定调用哪个API
            let res
            if (isEdit) {
              console.log(`调用更新API，ID: ${postData.id}`)
              res = await updateAskByIdApi(postData).catch((error) => {
                console.error('更新API错误:', error)
                return { code: 0, msg: error.message || '网络错误' }
              })
            } else {
              console.log('调用新增API')
              res = await addAskApi(postData).catch((error) => {
                console.error('新增API错误:', error)
                return { code: 0, msg: error.message || '网络错误' }
              })
            }

            loading.close()

            // 处理响应
            if (res && res.code === 1) {
              this.$message.success(isEdit ? '修改成功' : '添加成功')
              this.dialogFormVisible = false
              this.applyForList() // 刷新列表
            } else {
              this.$message.error(
                res?.msg || (isEdit ? '修改失败' : '添加失败')
              )
            }
          } catch (error) {
            console.error(this.form.id ? '修改失败:' : '添加失败:', error)
            this.$message.error(
              `${this.form.id ? '修改' : '添加'}失败: ${
                error.message || '未知错误'
              }`
            )
          }
        } else {
          // 滚动到错误处
          this.$message.error('请完善表单信息')
        }
      })
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该需求申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delAskByIdApi(row.id)
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.applyForList() // 刷新列表
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败')
          }
        })
        .catch(() => {})
    },

    // 选择商品
    selectProduct(index, row) {
      this.$message({
        message: '选择商品，行索引：' + index,
        type: 'info'
      })
    },

    // 计算总数量
    calculateTotal() {
      this.totalQuantity = this.tableData.reduce((sum, item) => {
        return sum + (Number(item.quantity) || 0)
      }, 0)
    },

    // 表格复选框选择
    handleSelectionChange(val) {
      this.selectionRow = val
      console.log(this.selectionRow)
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.applyForList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.applyForList()
    },

    // 上传前的验证
    // beforeUpload(file) {
    //   const isImage = file.type.startsWith("image/");
    //   if (!isImage) {
    //     this.$message.error("只能上传图片文件!");
    //     return false;
    //   }

    //   const isLt5M = file.size / 1024 / 1024 < 5;
    //   if (!isLt5M) {
    //     this.$message.error("上传图片大小不能超过 5MB!");
    //     return false;
    //   }
    //   return true;
    // },

    // 处理文件上传
    async handleUpload({ file }) {
      try {
        const formData = new FormData()
        formData.append('file', file)

        const res = await uploadFileApi(formData)

        if (res.code === 1) {
          // 获取文件名（从最后一个下划线后开始截取）
          const fileName = res.data.split('_').pop()
          this.uploadedFileName = fileName

          // 将完整路径存储到askUrl
          this.form.askUrl = res.data

          this.$message({
            type: 'success',
            message: '文件上传成功'
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '上传失败'
          })
        }
      } catch (error) {
        console.error('上传失败:', error)
        this.$message({
          type: 'error',
          message: '上传失败: ' + (error.message || '未知错误')
        })
      }
    },

    // 移除已上传的图片
    removeImage() {
      this.form.askUrl = ''
      this.uploadedFileName = ''
      this.$message({
        type: 'success',
        message: '图片已移除'
      })
    },

    // 商品选择改变时的处理函数
    async handleGoodsItemChange(goodsId, index) {
      // 如果没有选择仓库，提示并清空商品选择
      const item = this.form.goodsList[index]
      if (!item.warehouseId) {
        this.$message.warning('请先选择仓库')
        this.$nextTick(() => {
          item.goodsId = null
        })
        return
      }

      // 查找选择的商品
      const selectedGoods = this.goodsList.find((g) => g.id === goodsId)
      if (selectedGoods) {
        // 填充商品相关信息
        item.goodsName = selectedGoods.name
        item.goodsTypeName = selectedGoods.typeName || ''
        // 自动填充规格型号
        item.model = selectedGoods.model || ''
        // 设置默认数量为1
        item.number = 1
        // 如果有价格，自动计算金额
        if (selectedGoods.price) {
          item.unitPrice = selectedGoods.price
          this.updateMoney(index)
        } else {
          item.money = 0
        }

        // 获取库存信息 - 只传商品ID
        try {
          const res = await selGoodsNumberByIdApi(goodsId)
          if (res.code === 1) {
            // 更新库存数量
            item.stockNumber = res.data || 0
            console.log('库存信息:', item.stockNumber)
          } else {
            item.stockNumber = 0
            console.warn('获取库存信息失败:', res.msg)
          }
          return item
        } catch (error) {
          item.stockNumber = 0
          console.error('获取库存信息出错:', error)
        }
      }
    },

    // 更新金额
    updateMoney(index) {
      const item = this.form.goodsList[index]
      if (item.number && item.unitPrice) {
        item.money = item.number * item.unitPrice
      } else {
        item.money = 0
      }
    },

    // 修改fetchPriceAndUpdate方法
    async fetchPriceAndUpdate(goodsId, index) {
      try {
        const res = await selGoodsByIdApi(goodsId)
        if (res.code === 1 && res.data && res.data.price) {
          const price = parseFloat(res.data.price)
          const number = parseFloat(this.form.goodsList[index].number)

          // 直接计算金额，不进行取整或格式化
          const money = price * number

          // 直接赋值，不使用格式化
          this.$set(this.form.goodsList[index], 'money', money)
          this.$forceUpdate()
        }
      } catch (error) {
        console.error('获取商品价格失败:', error)
      }
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning', // 待审核
        1: 'primary', // 审核中
        2: 'success', // 已审核
        '-1': 'danger' // 已驳回
      }

      return statusMap[status] || 'info'
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '审核中',
        2: '已审核',
        '-1': '已驳回'
      }

      return statusMap[status] || '未知状态'
    },

    // 格式化价格
    formatPrice(price) {
      // 不强制格式化为两位小数，直接返回价格
      return '￥' + price

      // 如果需要添加千分位分隔符但不限制小数位数：
      // return "￥" + price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },

    // 添加商品
    addGoodsItem() {
      this.form.goodsList.push({
        goodsId: '',
        number: 1,
        money: ''
      })
      this.goodsQuery = {
        goodsTypeId: null,
        name: '',
        page: 1,
        pageSize: 9999,
        supplierId: null,
        warehouseId: null
      }
      this.selGoodsList()
      // 添加后触发验证
      this.$nextTick(() => {
        this.$refs['demandForm'].validateField('goodsList')
      })
    },

    // 移除商品
    removeGoodsItem(index) {
      if (this.form.goodsList.length > 1) {
        this.form.goodsList.splice(index, 1)
        // 删除后触发验证
        this.$nextTick(() => {
          this.$refs['demandForm'].validateField('goodsList')
        })
      } else {
        this.$message.warning('至少需要一项商品')
      }
    },

    // 远程搜索商品
    remoteSearchGoods(query) {
      if (query) {
        this.goodsLoading = true

        // 只更新name参数，不影响model参数
        this.goodsQuery.name = query

        this.selGoodsList().finally(() => {
          this.goodsLoading = false
        })
      }
    },

    // 处理部门改变
    handleDepartmentChange(value) {
      console.log('部门改变:', value)
      this.listQuery.departmentId = value
      this.applyForList()
    },

    // 处理部门选择变化 - 立即验证
    onDepartmentChange(value) {
      if (!value) return

      // 立即验证选择是否有效
      const node = this.findNodeById(this.departmentList, value)

      if (node && !node.parent) {
        // 如果选择了第一层，显示警告并重置
        this.$message.warning('请选择具体的子部门，不能选择顶层组织')

        // 延迟重置，确保用户能看到警告
        setTimeout(() => {
          this.form.needDepartmentId = ''
          // 强制触发验证
          this.$refs['demandForm'].validateField('needDepartmentId')
        }, 100)
      }
    },

    // 根据ID查找节点 - 确保考虑到深层结构
    findNodeById(data, id) {
      if (!data || !id) return null

      for (const item of data) {
        if (item.id === id) {
          return item
        }

        if (item.list && item.list.length > 0) {
          const found = this.findNodeById(item.list, id)
          if (found) {
            return found
          }
        }
      }
      return null
    },

    // 验证商品明细
    validateGoodsList(rule, value, callback) {
      if (!value || value.length === 0) {
        return callback(new Error('请至少添加一项商品'))
      }

      // 检查每个商品项
      for (let i = 0; i < value.length; i++) {
        const item = value[i]
        if (!item.goodsId) {
          return callback(new Error(`第${i + 1}项商品未选择商品`))
        }
        if (!item.number || item.number <= 0) {
          return callback(new Error(`第${i + 1}项商品未设置数量或数量无效`))
        }
        // 可以根据需要增加对money的验证
      }

      callback() // 验证通过
    },

    // 处理负责人选择
    onDirectorFocus() {
      this.directorLoading = true
      this.searchDirectors('')
    },

    // 搜索负责人
    async searchDirectors(query) {
      try {
        const res = await selStaffListApi({
          page: 1,
          pageSize: 9999,
          name: query
        })
        this.directorList = res.records || []
      } catch (error) {
        console.error('搜索负责人失败:', error)
        this.$message.error('搜索负责人失败')
        this.directorList = []
      } finally {
        this.directorLoading = false
      }
    },
    // 根据关键词搜索部门
    async searchDepartmentByKeyword(keyword) {
      this.departmentLoading = true
      try {
        // 设置查询条件
        const deptQuery = {
          page: 1,
          pageSize: 9999,
          name: keyword
        }

        // 调用API搜索部门
        const res = await selDepartmentListApi(deptQuery)
        if (res.code === 1) {
          // 更新部门列表
          this.departmentList = res.data || []
        }
      } catch (error) {
        console.error('搜索部门失败:', error)
      } finally {
        this.departmentLoading = false
      }
    },

    // 部门筛选方法
    filterDepartment(node, keyword) {
      // 关键词为空时返回true以显示全部节点
      if (!keyword) return true
      // 调用API搜索部门（延迟搜索以避免频繁请求）
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.searchDepartmentByKeyword(keyword)
      }, 300)

      // 将node的值转为字符串进行检索比较
      const targetText = node.name || ''
      return targetText.toLowerCase().includes(keyword.toLowerCase())
    },

    // 添加部门选择器失去焦点后重新加载数据的方法
    onDepartmentBlur() {
      // 当离开焦点时重新加载完整的部门列表
      this.departmentLoading = true
      setTimeout(() => {
        this.getAllDepartments()
      }, 200) // 稍微延迟以确保UI更新完成
    },

    // 获取所有部门数据
    async getAllDepartments() {
      try {
        // 设置查询条件 - 不带关键词搜索所有部门
        const deptQuery = {
          page: 1,
          pageSize: 9999
        }

        // 调用API获取所有部门
        const res = await selDepartmentListApi(deptQuery)
        if (res.code === 1) {
          // 更新部门列表
          this.departmentList = res.data || []
        }
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.$message.error('获取部门列表失败')
      } finally {
        this.departmentLoading = false
      }
    },

    // 部门获取焦点时的处理
    onDepartmentFocus() {
      if (!this.departmentList || this.departmentList.length === 0) {
        this.departmentLoading = true
        this.getAllDepartments()
      }
    },

    // 处理新增审核
    handleAddPurchase(row) {
      console.log('row', row)
      this.currentRow = row
      this.taxRateForm.taxRate = '' // 使用已有税率或默认值
      this.taxRateDialogVisible = true
    },

    // 添加确认税率方法
    async confirmTaxRate() {
      try {
        const row = this.currentRow
        if (!row) {
          this.$message.error('未找到选中行数据')
          return
        }

        const taxRateValue = parseFloat(this.taxRateForm.taxRate)

        // 从行数据中提取商品列表
        const goodsList = row.list
          ? row.list.map((item) => {
            return {
              goodsId: item.goodsId,
              number: item.number,
              taxPrice: item.money || 0,
              taxRate: taxRateValue, // 使用弹框中输入的税率
              totalPrice: item.totalPrice || item.money || 0,
              totalTaxPrice: item.totalTaxPrice || item.money || 0,
              unitPrice: item.money / item.number || 0,
              warehouseId: item.warehouseId || 0
            }
          })
          : []

        // 构造API请求参数
        const params = {
          buyGoodsGoodsDTOS: goodsList,
          askId: row.id || '',
          directorId: row.directorId || '',
          operatorId: row.operatorId || '',
          remark: row.remark || ''
        }

        // 调试输出检查参数
        console.log('准备发送的参数:', JSON.stringify(params))

        // 关闭税率弹框
        this.taxRateDialogVisible = false

        // 显示确认对话框
        this.$confirm('确定要创建审核通过的购货单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            // 调用API
            this.$loading({
              lock: true,
              text: '提交中...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })

            const res = await addOKBuyGoodsApi(params)
            this.$loading().close()

            if (res.code === 1) {
              this.$message.success('新增审核成功')
              this.$router.push({
                name: 'purchaseOrder'
              })
              this.applyForList() // 刷新列表
            } else {
              this.$message.error(res.msg || '新增审核失败')
            }
          })
          .catch(() => {
            this.$message.info('已取消操作')
          })
      } catch (error) {
        console.error('新增审核失败:', error)
        this.$message.error('新增审核失败: ' + (error.message || '未知错误'))
        this.taxRateDialogVisible = false
      }
    },

    // 处理规格型号失去焦点事件
    handleModelBlur(model, index) {
      if (!model) return

      // 设置查询参数中的model字段
      this.goodsQuery.model = model

      // 查询商品列表
      this.goodsLoading = true
      this.selGoodsList()
    },

    // 判断是否可以显示新增购货按钮
    canAddPurchase(row) {
      // 根据实际业务逻辑修改此条件
      return row.status === 2 // 举例：如果状态为"已审核"(2)则显示按钮
    },

    // 商品名称输入框失焦时触发
    async handleGoodsNameBlur() {
      if (!this.goodsName.trim()) return // 如果为空则不处理

      try {
        console.log('商品名称失焦，获取最新商品列表')
        // 调用获取商品列表的API
        const params = {
          name: this.goodsName.trim()
          // 可能需要添加其他参数
        }

        // 显示加载提示
        const loading = this.$loading({
          lock: true,
          text: '加载商品列表...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 调用获取商品列表的API
        const res = await getGoodsList(params)

        // 关闭加载提示
        loading.close()

        if (res && res.code === 1) {
          this.goodsList = res.data || []
          console.log('获取到的商品列表：', this.goodsList)
        } else {
          this.$message.warning(res.message || '获取商品列表失败')
        }
      } catch (error) {
        this.$loading().close()
        this.$message.error(
          '获取商品列表失败: ' + (error.message || '未知错误')
        )
        console.error('获取商品列表错误：', error)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.search-label {
  margin-right: 10px;
  white-space: nowrap;
}

.search-select {
  width: 200px;
}

.date-item {
  width: 350px;
}

.date-picker {
  width: 100%;
}

.search-actions {
  display: flex;
  align-items: center;
}

.search-button {
  margin-left: 10px;
}

.reset-button {
  margin-left: 10px;
}

.table-operations-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-operations {
  margin-bottom: 15px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.shopping-entry {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  align-items: center;
}

.entry-buttons {
  display: flex;
}

.circle-btn {
  margin-right: 10px;
  border-radius: 20px;
}

.attachment-info {
  display: flex;
  align-items: center;
  padding: 10px 0;

  .upload-link {
    display: flex;
    align-items: center;
    cursor: pointer;
    margin-right: 20px;

    i {
      margin-right: 5px;
    }

    &:hover {
      opacity: 0.8;
    }
  }

  .file-name {
    display: flex;
    align-items: center;
    margin-right: 20px;
    color: #606266;
    font-size: 14px;

    i {
      margin: 0 5px;

      &.el-icon-delete {
        color: #f56c6c;
        cursor: pointer;

        &:hover {
          opacity: 0.8;
        }
      }
    }
  }

  .order-number {
    color: #606266;
    font-size: 14px;
  }
}

.product-header {
  display: flex;
  align-items: center;
}

.required-mark {
  color: #f56c6c;
  margin-right: 4px;
}

.product-select {
  color: #409eff;
  cursor: pointer;
}

.product-image {
  width: 50px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image img {
  max-width: 100%;
  max-height: 100%;
}

.batch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.batch-tag {
  background-color: #909399;
  color: white;
  font-size: 10px;
  padding: 0 4px;
  border-radius: 2px;
}

.info-header {
  display: flex;
  align-items: center;
}

.info-header .el-icon-question {
  margin-left: 4px;
  color: #909399;
  cursor: help;
}

/* 合计行 */
.summary-row {
  display: flex;
  background-color: #fdf6ec;
  padding: 10px 15px;
  font-weight: bold;
  border: 1px solid #ebeef5;
  border-top: none;
}

.summary-label {
  width: 50px;
}

/* 备注区域 */
.remark-container {
  margin-bottom: 20px;
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

/* 金额信息区域 */
.amount-container {
  margin-bottom: 20px;
}

.amount-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.amount-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.amount-label {
  white-space: nowrap;
  margin-right: 5px;
  width: 80px;
  text-align: right;
}

.amount-input {
  width: 120px;
}

.amount-input.wider {
  width: 150px;
}

/* 底部工具栏 */
.footer-toolbar {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.blue-text {
  color: #409eff;
}

.history-buttons .history-btn {
  margin-left: 10px;
}

.blue-radio.el-radio ::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #409eff;
}

.address-edit {
  margin-left: 5px;
  cursor: pointer;
  color: #409eff;
}

// 上传组件样式
.upload-demo {
  :deep(.el-upload) {
    display: inline-block;
  }
}

// 响应式样式
@media screen and (max-width: 768px) {
  .attachment-info {
    flex-direction: column;
    align-items: flex-start;

    > * {
      margin-bottom: 10px;
    }
  }
}

// 图片上传样式
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409eff;
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

// 确保图片预览框大小一致
.el-upload {
  width: 120px;
  height: 120px;
  line-height: 120px;
}

.upload-demo {
  :deep(.el-upload) {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      height: 200px;

      .el-icon-upload {
        margin-top: 40px;
        font-size: 48px;
        color: #409eff;
      }

      .el-upload__text {
        margin-top: 20px;
        color: #606266;

        em {
          color: #409eff;
          font-style: normal;
          cursor: pointer;
        }
      }
    }
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 10px;
  }
}

// 图片预览样式
.upload-preview {
  position: relative;
  margin-top: 15px;
  width: 200px;
  height: 200px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .el-icon-delete {
    position: absolute;
    top: 5px;
    right: 5px;
    padding: 5px;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    cursor: pointer;
    font-size: 16px;
    transition: all 0.3s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .upload-demo {
    :deep(.el-upload-dragger) {
      height: 160px !important;
    }
  }

  .upload-preview {
    width: 160px;
    height: 160px;
  }
}

.uploaded-file-info {
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .file-name {
    color: #606266;
    font-size: 14px;
    word-break: break-all;
    flex: 1;
    margin-right: 10px;
  }

  .el-icon-delete {
    color: #f56c6c;
    cursor: pointer;
    font-size: 16px;

    &:hover {
      opacity: 0.8;
    }
  }
}

.goods-table-container {
  width: 100%;
  margin-bottom: 10px;
}

.add-goods-btn {
  margin-top: 10px;
  text-align: center;
}

.mb-0 {
  margin-bottom: 0;
}

.uploaded-file-info {
  margin-top: 10px;
  display: flex;
  align-items: center;

  .file-name {
    margin-right: 8px;
  }

  .el-icon-delete {
    color: #f56c6c;
    cursor: pointer;
  }
}

.operation-buttons {
  display: flex;
  justify-content: space-around;
  width: 100%;
  padding: 0 5px;
}

.button-container {
  width: 70px;
}

.button-placeholder {
  width: 70px;
  height: 28px;
}

.operation-buttons .el-button {
  padding: 7px 8px;
  width: 100%;
  font-size: 12px;
}

.operation-buttons > div {
  flex: 1;
  max-width: 75px;
  margin: 0 5px;
}

/* 内嵌表格样式 */
.inner-table {
  border: none !important;
  margin: 0;
  padding: 0;
}

.inner-table .el-table__row {
  background-color: transparent;
}

.inner-table td {
  border-bottom: 1px solid #f0f0f0;
  padding: 5px 0;
}

.inner-table tr:last-child td {
  border-bottom: none;
}

.goods-name {
  font-weight: 500;
  color: #303133;
}

.goods-type {
  color: #606266;
}

.goods-number {
  color: #409eff;
}

.goods-money {
  color: #f56c6c;
  font-weight: 500;
}

.no-goods {
  color: #909399;
  padding: 10px 0;
}

.goods-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: left;
  padding: 5px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-name {
  width: 120px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.goods-type {
  width: 120px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-number {
  width: 100px;
  color: #606266;

  .number-value {
    color: #409eff;
    font-weight: 500;
  }
}

.goods-money {
  width: 100px;
  color: #f56c6c;
  font-weight: 500;
}

/* 按钮容器样式 */
.btn-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 5px;
}

/* 操作按钮统一样式 */
.operation-btn {
  min-width: 64px;
}

.goods-option-layout {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
}

.goods-name {
  flex: 1;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 10px;
}

.goods-model {
  flex: 1;
  text-align: center;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-price {
  flex: 1;
  text-align: right;
  color: #f56c6c;
  font-weight: 500;
  padding-left: 10px;
}

/* 在style部分添加 - 注意这里不使用scoped以确保能影响弹出层 */
.goods-select-dropdown {
  min-width: 400px !important;
  width: 400px !important;
}

/* 确保搜索状态下的下拉菜单也有相同宽度 */
.el-select-dropdown.goods-select-dropdown .el-select-dropdown__wrap,
.el-select-dropdown.goods-select-dropdown .el-scrollbar__view,
.el-select-dropdown.goods-select-dropdown .el-select-dropdown__list {
  width: 100% !important;
}

/* 确保下拉菜单选项容器是正确宽度 */
.el-select-dropdown.goods-select-dropdown .el-select-dropdown__item {
  width: 100% !important;
  white-space: normal;
  height: auto;
  line-height: 1.5;
  padding: 8px 10px;
}

/* 确保输入搜索状态下弹出的菜单也有相同宽度 */
body > .el-select-dropdown.goods-select-dropdown {
  min-width: 400px !important;
  width: 400px !important;
}

/* 处理三列内容的布局，确保在搜索状态下也正确显示 */
.goods-option-layout {
  width: 100%;
  display: flex !important;
  justify-content: space-between !important;
}
</style>
